/*
 * s_nor_flash.c
 *
 *  Created on: Sep 11, 2020
 *      Author: hemingway
 */
#include "s_nor_flash.h"

#include <stdlib.h>
#include <stdbool.h>

#include "flash_interface.h"

#include <stdio.h>
#include <string.h>

#include "h_cc2640r2f_define.h"

#define S_NOR_FLASH_START_ADDR				15728640 //15 * 1024 * 1024
#define S_NOR_FLASH_END_ADDR				16777216 //16 * 1024 * 1024


signed char S_Nor_Flash_Init(void)
{
    flash_open();
    flash_close();
    return 0;
}

signed char S_Nor_Flash_Write_Para_Struct(unsigned char *data, unsigned short len)
{
	unsigned char rslt = 0U;

	unsigned short clear_page_num = 1U, i = 0;

	if(len >= 4096)
	{
		clear_page_num = len / 4096;
		if(len % 4096)
		{
			clear_page_num++;
		}
	}

	// Not more than 16Mbit
	clear_page_num = clear_page_num > 255 ? 255 : clear_page_num;

	flash_open();

	for(i = 0; i < clear_page_num; i++)
	{
		rslt = eraseFlashPgNew((S_NOR_FLASH_START_ADDR / 4096) + i);
	}

	if(rslt)
	{
		flash_close();
		return (-2);
	}

	rslt = writeFlash(S_NOR_FLASH_START_ADDR, data, len);

	flash_close();

	if(rslt)
	{
		return (-1);
	}
	else
	{
		return 0;
	}
}

signed char S_Nor_Flash_Read_Para_Struct(unsigned char *data, unsigned short len)
{
	unsigned char rslt = 0U;

	flash_open();

	rslt = readFlash(S_NOR_FLASH_START_ADDR, data, len);

	flash_close();

	if(rslt)
	{
		return (-1);
	}
	else
	{
		return 0;
	}
}




#define EACH_DATA_LEN			128
signed char S_Nor_Flash_Test_old(void)
{
	flash_open();

	unsigned char rdata[EACH_DATA_LEN];
	unsigned int i = 0;

	for(i = 0; i < EACH_DATA_LEN; i++)
	{
		rdata[i] = i;
	}


	
	// printf("eraese new state: 0x%02x\r\n", eraseFlashPgByAddr(S_NOR_FLASH_START_ADDR, EACH_DATA_LEN));
	

	printf("Write state: 0x%02x\r\n", writeFlash(S_NOR_FLASH_START_ADDR, rdata, EACH_DATA_LEN));

	printf("eraese state: 0x%02x\r\n", eraseFlashPgNew(S_NOR_FLASH_START_ADDR / 4096));

	memset(rdata, '0xFF', EACH_DATA_LEN);


	printf("Read state: 0x%02x\r\n", readFlash(S_NOR_FLASH_START_ADDR, rdata, EACH_DATA_LEN));

	debug_hex(rdata, EACH_DATA_LEN);

	// for(i = 0xe10000; i < 16777216; i+= EACH_DATA_LEN)
	// {
	// 	readFlash(i, rdata, EACH_DATA_LEN);
	// 	if(s_nor_flash_block_data_check(rdata, 0xFF, EACH_DATA_LEN))
	// 	{
	// 		printf("the i is 0x%x\r\n", i);
	// 	}
	// 	// else
	// 	// {
	// 	// 	printf(".");
	// 	// 	fflush(stdout);
	// 	// }
	// 	// eraseFlashPg(i);
		
	// }


	

	flash_close();
	return 0;
}

signed char S_Nor_Flash_Test(void)
{
	unsigned char rdata[EACH_DATA_LEN];
//	unsigned int i = 0;

	// for(i = 0; i < EACH_DATA_LEN; i++)
	// {
	// 	rdata[i] = i + 2;
	// }

	// S_Nor_Flash_Write_Para_Struct(rdata, EACH_DATA_LEN);

	memset(rdata, 0xFF, EACH_DATA_LEN);


	S_Nor_Flash_Read_Para_Struct(rdata, EACH_DATA_LEN);

	debug_hex(rdata, EACH_DATA_LEN);
}

